package com.zlx.mall.biz.access.aspect;

import com.zlx.mall.basic.annotations.ValidateToken;
import com.zlx.mall.basic.common.exception.ExceptionWrapper;
import com.zlx.mall.basic.common.exception.IllegalRequestArgumentException;
import com.zlx.mall.basic.common.holder.ValidatorHolder;
import com.zlx.mall.basic.common.model.SystemParam;
import com.zlx.mall.basic.util.json.JacksonUtil;
import com.zlx.mall.basic.web.holder.RequestContextHolder;
import com.zlx.mall.basic.web.model.BaseRequest;
import com.zlx.mall.biz.access.constant.AccessConstants;
import com.zlx.mall.biz.access.holder.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Optional;

/**
 * @author qingke
 **/
@Slf4j
@Aspect
@Component
@Order(1)
public class AccessAspect {

    @Pointcut(value = "(@annotation(org.springframework.web.bind.annotation.RequestMapping)" +
            "||@annotation(org.springframework.web.bind.annotation.PostMapping)) " +
            "||@annotation(org.springframework.web.bind.annotation.GetMapping)")
    private void pointcut() {}

    @Before("pointcut()")
    public void doBefore(JoinPoint point) {
        ValidateToken annotation = ((MethodSignature) point.getSignature()).getMethod().getAnnotation(ValidateToken.class);
        try {
            String systemParamContext = Optional
                    .ofNullable(RequestContextHolder.getHeader(AccessConstants.HEADER_NAME_ACCESS_TOKEN))
                    .filter(StringUtils::hasText)
                    .orElseThrow(() -> new IllegalRequestArgumentException("System Data must not be null"));

            SystemParam systemParam = ExceptionWrapper.wrap(
                    () -> JacksonUtil.toObject(systemParamContext, SystemParam.class),
                    IllegalRequestArgumentException::new);

            ValidatorHolder.validate(systemParam, IllegalRequestArgumentException::new);

            for (Object arg : point.getArgs()) {
                if (arg instanceof BaseRequest) {
                    ((BaseRequest) arg).setSystem(systemParam);
                    break;
                }
            }

            UserContextHolder.setSystemParam(systemParam);

        } catch (Exception e) {
            if (annotation != null && annotation.validate()) {
                throw e;
            }
        }
    }

}
